package org.infinitest.intellij.idea.window;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import org.infinitest.intellij.*;
import org.infinitest.intellij.idea.IdeaCompilationNotifier;
import org.infinitest.intellij.idea.IdeaModuleSettings;
import org.infinitest.intellij.idea.IdeaProjectCompiler;
import org.infinitest.intellij.idea.language.IdeaInfinitestAnnotatorLocator;
import org.infinitest.intellij.idea.facet.FacetListener;
import org.jetbrains.annotations.NotNull;

public class InfinitestToolWindowComponent implements ModuleComponent, InfinitestToolWindow, FacetListener
{
  public static final String TOOL_WINDOW_ID = "Infinitest";

  private InfinitestRunner runner;
  private Project project;

  private boolean projectOpened;

  /**
   * This is the constructor used by the IntelliJ plugin system
   *
   * @param project The active project
   * @param module  The active module
   */
  public InfinitestToolWindowComponent(Project project, Module module)
  {
    this(new IdeaModuleSettings(module), new IdeaToolWindowRegistry(project),
      new IdeaCompilationNotifier(project), new IdeaProjectCompiler(project));
    this.project = project;
  }

  public InfinitestToolWindowComponent(ModuleSettings moduleSettings, ToolWindowRegistry toolWindowRegistry,
    CompilationNotifier compilationNotifier, ProjectCompiler compiler)
  {
    this.runner = new InfinitestRunner(moduleSettings, toolWindowRegistry, compilationNotifier, compiler,
      new IdeaInfinitestAnnotatorLocator());
  }

  public void initComponent()
  {
  }

  public void disposeComponent()
  {
  }

  @NotNull
  public String getComponentName()
  {
    return "org.infinitest.intellij.idea.window.InfinitestToolWindowComponent";
  }

  public void startInfinitest()
  {
    runner.run();
  }

  public void stopInfinitest()
  {
    runner.stop();
  }

  public void startInfinitestAfterStartup()
  {
    StartupManager.getInstance(project).registerPostStartupActivity(runner);
  }

  public void facetInitialized()
  {
    if (projectOpened)
    {
      startInfinitest();
    }
    else
    {
      startInfinitestAfterStartup();
    }
  }

  public void facetDisposed()
  {
    stopInfinitest();
  }

  public void projectOpened()
  {
    projectOpened = true;
  }

  public void projectClosed()
  {
    stopInfinitest();
  }

  public void moduleAdded()
  {
  }
}
